package org.ace.communicate
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.text.TextField;
	
	import org.ace.model.SocketModel;
	
	import org.osmf.logging.Logger;
	import org.osmf.logging.LoggerFactory;
	
	

	public class SocketCommunicate
	{
		private static var sc:SocketCommunicate;
		private var socket:Socket;
		private var address:String="110.76.47.19";
		private var port:int=10101;
		public static var isConn:Boolean=false;
		public function SocketCommunicate(){
			socket=new Socket();
			socket.addEventListener(Event.CONNECT,onConn);
			socket.addEventListener(IOErrorEvent.IO_ERROR,onError);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurity);
			socket.connect(address,port);
			
		}
		public static function getSocket():SocketCommunicate{
			if(sc==null){
				sc=new SocketCommunicate();
			}
			return sc;
		}
		
		public function onConn(e:Event):void{
			socket.removeEventListener(Event.CONNECT,onConn);
			socket.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurity);
			socket.addEventListener(Event.CLOSE,onClose);
			socket.addEventListener(ProgressEvent.SOCKET_DATA,onData);
			isConn=true;
			
		}
		public function onError(e:IOErrorEvent):void{
			socket.removeEventListener(Event.CONNECT,onConn);
			socket.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurity);
			isConn=false;
		}
		public function onSecurity(e:SecurityErrorEvent):void{
			socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurity);
			socket.removeEventListener(Event.CONNECT,onConn);
			socket.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			socket.close();
			isConn=false;
			
		}
		public function onClose(e:Event):void{
			socket.removeEventListener(Event.CLOSE,onClose);
			isConn=false;
		}
		
		public function write(message:SocketModel):void{
			if(isConn){
				socket.writeInt(message.type);
				socket.writeInt(message.area);
				socket.writeInt(message.command);
				socket.writeObject(message.message);
				socket.flush();
			}else{
				
			}
		}
		public function onData(e:ProgressEvent):void{
			while(socket.bytesAvailable){
				var type:int=socket.readInt();
				var area:int=socket.readInt();
				var command:int=socket.readInt();
				var o:Object=socket.readObject();
				var model:SocketModel=new SocketModel(type,area,command,o);
				MessageReceived.getMessageReceived().received(model);
			}
		}
	}
}